from django import forms
from django.core.exceptions import ValidationError
from web import models
class BaseForm(object):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,item in self.fields.items():
            item.widget.attrs['class']='form-control'
            item.widget.attrs['placeholder']=f'请输入{item.label}'

class FileFoldForm(BaseForm,forms.ModelForm):
    class Meta:
        model=models.FileRepository
        fields = ['name',]

    def __init__(self,request,parent_obj,*args,**kwargs):
        super().__init__(* args, ** kwargs)
        self.request=request
        self.parent_obj = parent_obj
    def clean_name(self):
        name=self.cleaned_data['name']

        if self.parent_obj:

            exists=models.FileRepository.objects.filter(file_type=2,
                                                        name=name,
                                                        project=self.request.tracer.project,
                                                        parent=self.parent_obj).exists()

        else:
            exists = models.FileRepository.objects.filter(file_type=2,
                                                          name=name,
                                                          project=self.request.tracer.project,
                                                          parent__isnull=True).exists()

        if exists:
            raise ValidationError('文件夹存在')
        else:
            return name